package com.common.www.utils.sms;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import lombok.Getter;
import lombok.Setter;

public class SmsUtils {
    /**
     * 发送短信
     */
    public static void sendSms(String phone, TemplateSms templateSms, OnSengSmsListener onSengSmsListener) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4Fbsx68b7Ldj4bkDpnYX", "A1etJsOL0PInezGkN4YFzsyHzBDJR9");//此信息设置后不可修改，且不可查看（阿里云后台）
//        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "迈乐");
        request.putQueryParameter("TemplateCode", templateSms.getCode());
        request.putQueryParameter("TemplateParam", templateSms.getJsonContent());
        try {
            CommonResponse response = client.getCommonResponse(request);
            if (onSengSmsListener != null) {
                onSengSmsListener.success(JSON.parseObject(response.getData(), ResponseSms.class));
                System.out.println(response.getData());
            }
        } catch (ServerException e) {
            if (onSengSmsListener != null)
                onSengSmsListener.fail(e);
            e.printStackTrace();
        } catch (ClientException e) {
            if (onSengSmsListener != null)
                onSengSmsListener.fail(e);
            e.printStackTrace();
        }
    }

    @Getter
    @Setter
    public static class ResponseSms {
        private String Message;
        private String RequestId;
        private String BizId;
        private String Code;
    }

    public interface OnSengSmsListener {
        void success(ResponseSms responseSms);

        void fail(Exception e);
    }
}
